package com.atguigu.spzx.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    // 请求之前进行执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      // 如果是OPTIONS 请求,直接方形   OPTIONS:预检请求
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
      //如果是正常请求,获取token
        String token = request.getHeader("token");
        //如果不存在token
        if(StringUtils.isEmpty(token)) {
            responseNoLoginInfo(response) ;
            return false ;
        }

        // 查询redis 是否存在当前登录信息
        String sysUserStr = redisTemplate.opsForValue().get("user:login" + token);
        if (StringUtils.isEmpty(sysUserStr)){
            //如果不存在当前登录信息
            responseNoLoginInfo(response) ;
            return false ;
        }
        //如果存在当前登录信息
        //将信息存储在ThreadLocal
        SysUser sysUser = JSON.parseObject(sysUserStr, SysUser.class);
        AuthContextUtil.set(sysUser);
        //刷新redis存储时间
        redisTemplate.expire("user:login" + token,30, TimeUnit.MINUTES);
        //放行
        return true;
    }

    //所有方法完成之后进行和执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }
}
